package cn.goour.web.sys.filter

import cn.goour.web.sys.entity.Admin
import cn.goour.web.sys.repository.AdminRepository
import cn.goour.web.sys.repository.UserRepository
import org.slf4j.LoggerFactory
import org.springframework.web.context.support.WebApplicationContextUtils
import setAdmin
import javax.servlet.*
import javax.servlet.annotation.WebFilter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse


//@Component
@WebFilter(filterName = "AdminLoginFilter", urlPatterns = arrayOf("/admin/*"))
open class AdminLoginFilter : Filter {
    lateinit var repository: AdminRepository

    override fun destroy() {
    }

    override fun doFilter(p0: ServletRequest?, p1: ServletResponse?, p2: FilterChain?) {
        val request = p0 as HttpServletRequest
        val response = p1 as HttpServletResponse
        try {
            var obj = request.session.getAttribute("admin")
            if (obj != null && obj is Admin) {
                obj = repository.findOne(obj.id)
                if (obj != null && obj.login) {
                    request.setAdmin(obj)
                    p2!!.doFilter(p0, p1)
                } else {
                    logger.info("不是管理员或者不允许登录")
                    request.session.removeAttribute("admin")
                    response.sendRedirect(request.contextPath + "/adminLogin")
                }
            } else {
                logger.info("obj=null或者不是Admin")
                request.session.removeAttribute("admin")
                response.sendRedirect(request.contextPath + "/adminLogin")
            }
        } catch (e: Exception) {
            e.printStackTrace()
            request.session.removeAttribute("admin")
            response.sendRedirect(request.contextPath + "/adminLogin")
        }


    }

    override fun init(p0: FilterConfig?) {
        val servletContext = p0?.servletContext//ServletContext
        val ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext)
        repository = ctx?.getBean(AdminRepository::class.java) as AdminRepository

    }

    companion object {
        private val logger = LoggerFactory.getLogger(AdminLoginFilter::class.java)
    }
}